<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="90%"
    :before-close="handleClose"
    class="resume-preview-dialog"
    :fullscreen="isFullscreen"
  >
    <div class="preview-container" v-loading="loading">
      <!-- 工具栏 -->
      <div class="preview-toolbar">
        <div class="toolbar-left">
          <el-button-group>
            <el-button
              :disabled="currentPage <= 1"
              @click="prevPage"
              size="small"
            >
              <el-icon><ArrowLeft /></el-icon>
              上一页
            </el-button>
            <el-button disabled size="small">
              {{ currentPage }} / {{ totalPages }}
            </el-button>
            <el-button
              :disabled="currentPage >= totalPages"
              @click="nextPage"
              size="small"
            >
              下一页
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </el-button-group>
        </div>

        <div class="toolbar-center">
          <el-button-group>
            <el-button @click="zoomOut" size="small" :disabled="zoomLevel <= 0.5">
              <el-icon><ZoomOut /></el-icon>
            </el-button>
            <el-button disabled size="small" class="zoom-display">
              {{ Math.round(zoomLevel * 100) }}%
            </el-button>
            <el-button @click="zoomIn" size="small" :disabled="zoomLevel >= 3">
              <el-icon><ZoomIn /></el-icon>
            </el-button>
            <el-button @click="resetZoom" size="small">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-button-group>
        </div>

        <div class="toolbar-right">
          <ThemeToggle />
          <el-button @click="toggleFullscreen" size="small">
            <el-icon><FullScreen /></el-icon>
            {{ isFullscreen ? '退出全屏' : '全屏' }}
          </el-button>
          <el-button type="primary" @click="handleDownload" size="small">
            <el-icon><Download /></el-icon>
            下载
          </el-button>
        </div>
      </div>

      <!-- PDF预览 -->
      <div v-if="fileType === 'pdf'" class="pdf-preview">
        <div v-if="pdfReady" class="pdf-container">
          <VuePdfEmbed
            ref="pdfRef"
            :source="pdfSource"
            :page="currentPage"
            :scale="zoomLevel"
            class="pdf-embed"
            @loaded="onPdfLoaded"
            @loading-failed="onPdfError"
          />
        </div>
        <div v-else-if="!loading && pdfError" class="preview-error">
          <el-result
            icon="warning"
            title="PDF预览失败"
            :sub-title="pdfError"
          >
            <template #extra>
              <el-button type="primary" @click="handleDownload">
                <el-icon><Download /></el-icon>
                下载文件
              </el-button>
            </template>
          </el-result>
        </div>
      </div>

      <!-- Word文档预览 -->
      <div v-else-if="fileType === 'docx' || fileType === 'doc'" class="docx-preview">
        <div v-if="docxReady" class="docx-container" ref="docxContainer">
          <!-- docx-preview会在这里渲染内容 -->
        </div>
        <div v-else-if="!loading && docxError" class="preview-error">
          <el-result
            icon="warning"
            title="Word文档预览失败"
            :sub-title="docxError"
          >
            <template #extra>
              <el-button type="primary" @click="handleDownload">
                <el-icon><Download /></el-icon>
                下载文件
              </el-button>
            </template>
          </el-result>
        </div>
      </div>

      <!-- 图片预览 -->
      <div v-else-if="isImageFile" class="image-preview">
        <div class="image-container">
          <img
            :src="fileUrl"
            alt="简历预览"
            class="preview-image"
            :style="{ transform: `scale(${zoomLevel})` }"
          />
        </div>
      </div>

      <!-- 其他文件类型 -->
      <div v-else class="unsupported-preview">
        <el-result
          icon="warning"
          title="不支持预览"
          sub-title="此文件类型不支持在线预览，请下载后查看"
        >
          <template #extra>
            <el-button type="primary" @click="handleDownload">
              <el-icon><Download /></el-icon>
              下载文件
            </el-button>
          </template>
        </el-result>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleDownload">
          <el-icon><Download /></el-icon>
          下载
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  ArrowRight,
  ZoomIn,
  ZoomOut,
  Download,
  Refresh,
  FullScreen
} from '@element-plus/icons-vue'
import VuePdfEmbed from 'vue-pdf-embed'
import { renderAsync } from 'docx-preview'
import ThemeToggle from './ThemeToggle.vue'

interface Props {
  visible: boolean
  fileUrl: string
  fileName: string
  title?: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'download'): void
}

const props = withDefaults(defineProps<Props>(), {
  title: '简历预览'
})

const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const zoomLevel = ref(1)
const isFullscreen = ref(false)

// PDF相关
const pdfRef = ref()
const pdfSource = ref<string | ArrayBuffer | null>(null)
const pdfReady = ref(false)
const pdfError = ref('')

// Word文档相关
const docxContainer = ref<HTMLElement>()
const docxReady = ref(false)
const docxError = ref('')

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
})

const fileType = computed(() => {
  const extension = props.fileName.split('.').pop()?.toLowerCase()
  return extension || ''
})

const isImageFile = computed(() => {
  return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileType.value)
})

// 监听文件URL变化
watch(() => props.fileUrl, async (newUrl) => {
  if (newUrl && props.visible) {
    await loadFile()
  }
}, { immediate: true })

watch(() => props.visible, async (newVisible) => {
  if (newVisible && props.fileUrl) {
    await loadFile()
  } else if (!newVisible) {
    resetPreview()
  }
})

// 加载文件
const loadFile = async () => {
  if (!props.fileUrl) return

  loading.value = true
  resetPreview()

  try {
    if (fileType.value === 'pdf') {
      await loadPDF()
    } else if (fileType.value === 'docx' || fileType.value === 'doc') {
      await loadDocx()
    } else if (isImageFile.value) {
      // 图片文件直接显示，无需特殊处理
      loading.value = false
    } else {
      loading.value = false
    }
  } catch (error) {
    console.error('文件加载失败:', error)
    loading.value = false
  }
}

// 重置预览状态
const resetPreview = () => {
  currentPage.value = 1
  totalPages.value = 1
  zoomLevel.value = 1
  pdfReady.value = false
  pdfError.value = ''
  docxReady.value = false
  docxError.value = ''
  pdfSource.value = null
}

// 加载PDF文件
const loadPDF = async () => {
  try {
    // 使用代理或直接fetch获取PDF数据
    let pdfUrl = props.fileUrl

    // 如果是后端的media文件，需要添加认证头
    const fetchOptions: RequestInit = {}
    if (pdfUrl.includes('/media/')) {
      const token = localStorage.getItem('access_token')
      if (token) {
        fetchOptions.headers = {
          'Authorization': `Bearer ${token}`
        }
      }
    }

    const response = await fetch(pdfUrl, fetchOptions)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const arrayBuffer = await response.arrayBuffer()
    pdfSource.value = arrayBuffer

  } catch (error) {
    console.error('PDF加载失败:', error)
    pdfError.value = '无法加载PDF文件，请检查网络连接或文件是否存在'
  } finally {
    loading.value = false
  }
}

// 加载Word文档
const loadDocx = async () => {
  try {
    if (!docxContainer.value) {
      await nextTick()
    }

    if (!docxContainer.value) {
      throw new Error('文档容器未找到')
    }

    // 获取文档数据
    let docxUrl = props.fileUrl

    const fetchOptions: RequestInit = {}
    if (docxUrl.includes('/media/')) {
      const token = localStorage.getItem('access_token')
      if (token) {
        fetchOptions.headers = {
          'Authorization': `Bearer ${token}`
        }
      }
    }

    const response = await fetch(docxUrl, fetchOptions)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const arrayBuffer = await response.arrayBuffer()

    // 使用docx-preview渲染文档
    await renderAsync(arrayBuffer, docxContainer.value, undefined, {
      className: 'docx-wrapper',
      inWrapper: true,
      ignoreWidth: false,
      ignoreHeight: false,
      ignoreFonts: false,
      breakPages: true,
      ignoreLastRenderedPageBreak: true,
      experimental: false,
      trimXmlDeclaration: true,
      useBase64URL: false,
      useMathMLPolyfill: false,
      showChanges: false,
      debug: false
    })

    docxReady.value = true

  } catch (error) {
    console.error('Word文档加载失败:', error)
    docxError.value = '无法加载Word文档，请检查网络连接或文件格式'
  } finally {
    loading.value = false
  }
}

// PDF事件处理
const onPdfLoaded = (pdf: any) => {
  totalPages.value = pdf.numPages
  pdfReady.value = true
  loading.value = false
}

const onPdfError = (error: any) => {
  console.error('PDF加载错误:', error)
  pdfError.value = '无法加载PDF文件'
  loading.value = false
}

// 页面控制
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 缩放控制
const zoomIn = () => {
  if (zoomLevel.value < 3) {
    zoomLevel.value += 0.25
  }
}

const zoomOut = () => {
  if (zoomLevel.value > 0.5) {
    zoomLevel.value -= 0.25
  }
}

const resetZoom = () => {
  zoomLevel.value = 1
}

// 全屏控制
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 事件处理
const handleClose = () => {
  emit('update:visible', false)
  resetPreview()
  isFullscreen.value = false
}

const handleDownload = () => {
  emit('download')
}
</script>

<style lang="scss" scoped>
.resume-preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    max-height: 80vh;
    overflow: hidden;
  }

  &:deep(.el-dialog--fullscreen) {
    .el-dialog__body {
      max-height: calc(100vh - 120px);
    }
  }
}

.preview-container {
  height: 80vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color-page);
  transition: background-color 0.3s ease;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--bg-color);
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--box-shadow-light);
  transition: all 0.3s ease;

  .toolbar-left,
  .toolbar-center,
  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .zoom-display {
    min-width: 60px;
    font-size: 12px;
    color: var(--text-color-secondary);
    font-weight: 500;
  }

  .el-button {
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
    }
  }
}

.pdf-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .pdf-container {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: auto;
    padding: 20px;

    .pdf-embed {
      box-shadow: var(--box-shadow);
      border-radius: 8px;
      background: var(--bg-color);
      border: 1px solid var(--border-color);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: var(--box-shadow-dark);
      }
    }
  }
}

.docx-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .docx-container {
    flex: 1;
    overflow: auto;
    padding: 24px;
    background: var(--bg-color);
    margin: 20px;
    border-radius: 12px;
    box-shadow: var(--box-shadow);
    border: 1px solid var(--border-color);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: var(--box-shadow-dark);
    }

    :deep(.docx-wrapper) {
      font-family: 'Microsoft YaHei', '微软雅黑', 'PingFang SC', Arial, sans-serif;
      line-height: 1.8;
      color: var(--text-color-primary);
      font-size: 14px;

      p {
        margin: 12px 0;
        color: var(--text-color-primary);
      }

      h1, h2, h3, h4, h5, h6 {
        margin: 20px 0 12px 0;
        font-weight: 600;
        color: var(--text-color-primary);
      }

      table {
        border-collapse: collapse;
        width: 100%;
        margin: 20px 0;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: var(--box-shadow-light);

        td, th {
          border: 1px solid var(--border-color);
          padding: 12px;
          text-align: left;
          color: var(--text-color-primary);
        }

        th {
          background-color: var(--bg-color-overlay);
          font-weight: 600;
          color: var(--text-color-primary);
        }

        tr:nth-child(even) {
          background-color: var(--bg-color-overlay);
        }
      }

      ul, ol {
        margin: 12px 0;
        padding-left: 28px;
        color: var(--text-color-primary);
      }

      li {
        margin: 6px 0;
        color: var(--text-color-primary);
      }

      strong, b {
        color: var(--text-color-primary);
        font-weight: 600;
      }

      em, i {
        color: var(--text-color-secondary);
      }
    }

    // 自定义滚动条
    &::-webkit-scrollbar {
      width: 8px;
    }

    &::-webkit-scrollbar-track {
      background: var(--bg-color-overlay);
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--border-color);
      border-radius: 4px;
      transition: background-color 0.3s ease;

      &:hover {
        background: var(--border-color-hover);
      }
    }
  }
}

.image-preview {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
  padding: 20px;

  .image-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100%;

    .preview-image {
      max-width: 100%;
      max-height: 100%;
      box-shadow: var(--box-shadow);
      border-radius: 8px;
      border: 1px solid var(--border-color);
      transition: all 0.3s ease;
      transform-origin: center;

      &:hover {
        box-shadow: var(--box-shadow-dark);
      }
    }
  }
}

.preview-error,
.unsupported-preview {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: var(--bg-color);
  margin: 20px;
  border-radius: 12px;
  border: 1px solid var(--border-color);
  box-shadow: var(--box-shadow-light);

  :deep(.el-result) {
    .el-result__title {
      color: var(--text-color-primary);
    }

    .el-result__subtitle {
      color: var(--text-color-secondary);
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  background: var(--bg-color-overlay);
  border-top: 1px solid var(--border-color);
  border-radius: 0 0 12px 12px;

  .el-button {
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .preview-toolbar {
    flex-direction: column;
    gap: 8px;
    padding: 8px;

    .toolbar-left,
    .toolbar-center,
    .toolbar-right {
      width: 100%;
      justify-content: center;
    }
  }

  .preview-container {
    height: 70vh;
  }

  .pdf-container,
  .docx-container,
  .image-container {
    padding: 10px;
  }
}
</style>
